<?php
class Api_DbTable_User extends Core_Db_Table_Abstract implements Core_Db_Crud_Interface {
	protected $_name = 'users';
	
	public function getAll($parent = null) {
		return $this->fetchAll ( $this->select () );
	}
	public function getBackUrl($id, $type = 0) {
		if ($type === 0)
			return null;
		return Zend_Controller_Front::getInstance ()->getRouter ()->assemble ( array ("controller" => "admin", "action" => "read", "name" => "user" ), null, true );
	}
	public function getMetaData($id) {
		return array ('username', 'password', 'price scheme', 'is admin' );
	}
	public function getOne($id) {
		return $this->fetchRow ( $this->select ( 'login, price_scheme, is_admin' )->where ( 'id = ?', $id ) );
	}
	public function getForm($id, $req = true) {
		return new Api_Form_User ( null, null, $req );
	}
	
	public function create_new_user($username, $password) {
		$data ['password'] = md5 ( $password );
		$data ['login'] = $username;
		$data ['price_scheme'] = 1;
		$data ['is_admin'] = 0;
		$this->insert ( $data );
	}	
	
	public function searchUser($email) {
		return $this->fetchRow ( $this->select ()->where ( 'login = ?', $email ) );
	}
	
	public function chengepass($email, $password) {
		$user = $this->fetchRow ( $this->select ()->where ( 'login = ?', $email ) );
		$data ['password'] = md5 ( $password );
		$data ['login'] = $user->login;
		$data ['price_scheme'] = $user->price_scheme;
		$data ['is_admin'] = $user->is_admin;
		$this->update ( $data, 'id = ' . $user->id );
	}
	
	public function create(Zend_Form $form, $parent = 0) {
		$data = $form->getValues ();
		$data ['password'] = md5 ( $data ['password'] );
		$this->insert ( $data );
	}
	public function edit(Zend_Form $form, $id) {
		$data = $form->getValues ();
		if (isset ( $data ['password'] ))
			$data ['password'] = md5 ( $data ['password'] );
		$this->update ( $data, 'id = ' . $id );
	}
	public function remove($id) {
		$this->delete ( 'id = ' . $id );
	}
}